TypeScript v4.7
2022/5/24
keyが変数で、obj[key]とした時にもtype guradされるようになった
code:ts
const key = 'a'
const numberOrString = Math.random() < 0.5 ? 42 : "hello";
const obj = {
'a': numberOrString,
};
if (typeof objkey === "string") { // 以前: objkey :: string | number // v4.7: objkey :: string }
// 以前は予め変数に束縛しておく必要があった
if (typeof a === "string") {
// 以前,v4.7: a :: string
}
Conditional Types(.. ? .. : ..)の条件分岐を簡略して書ける(場合ができた)
これめっちゃええやんmrsekut.icon*2
inとかoutとかin outとか書いてvarianceを明示できる
code:ts
interface State<in out T> {
get: () => T;
set: (value: T) => void;
}
ECMAScript Module Support in Node.js
4.5のだけど、保留になったやつ
普段から困ってないから読むモチベがわかないなmrsekut.icon
Control over Module Detection
Improved Function Inference in Objects and Methods
未読
code:ts
declare function f<T>(arg: {
produce: (n: string) => T,
consume: (x: T) => void
}): void;
// ①Works
f({
produce: () => "hello",
consume: x => x.toLowerCase()
});
// ②Works
f({
produce: (n: string) => n,
consume: x => x.toLowerCase(),
});
// ③Was an error, now works.
f({
produce: n => n,
consume: x => x.toLowerCase(),
});
// ④Was an error, now works.
f({
produce: function () { return "hello"; },
consume: x => x.toLowerCase(),
});
// ⑤Was an error, now works.
f({
produce() { return "hello" },
consume: x => x.toLowerCase(),
});
以前は、①がokで、④⑤がerrorだったのなんでだろう
4.7は①~⑤の全てがokになった
変更が地味に大きい
元々のコード例が、そんな嫌か?というかんじがするんだがmrsekut.icon
新しい構文が導入された感じになってる
genericな関数を、型の具体化をするための記法がある
JSならただ関数に新しい名前を付けただけ
まあ嬉しいけど、わざわざ追加するほどなのか?という気もする
PRで2つのissueがfixされているのでそれも読むと納得できそう
code:ts
interface Box<T> {
value: T;
}
function makeBox<T>(value: T) {
return { value };
}
type Hammer = string
type Wrench = string
// function makeHammerBox(hammer: Hammer) {
// return makeBox(hammer);
// }
// or...
// const makeWrenchBox: (wrench: Wrench) => Box<Wrench> = makeBox;
const makeHammerBox = makeBox<Hammer>;
const makeWrenchBox = makeBox<Wrench>;
genericなclassを具体化する
code:ts
const ErrorMap = Map<string, Error>;
このErrorMapはinstanceではなく、classの定義であることに注意mrsekut.icon
これによって型を具体化したclass ErrorMap extends Map<string, Error> {}が定義されている
こういうのも書けるようになった
code:ts
type BoxFunc<T> = typeof makeBox<T>; // (value: T) => { value: T }
type Box<T> = ReturnType<typeof makeBox<T>>; // { value: T }
type StringBox = Box<string>; // { value: string }
これはよさそう
resolution-mode
Groups-Aware Organize Imports
Object Method Snippet Completions
Breaking Changes